/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/string-to-integer-atoi
   @Language: C++
   @Datetime: 19-05-21 17:26
   */

class Solution {
public:
	int myAtoi(string &str) {
		long x=0;
		bool positive=true;
		for(int i=0; i<str.length(); ++i){
			if(str[i]==' ') continue;
			else if(str[i]=='+') ++i;
			else if(str[i]=='-'){
				positive=!positive;
				++i;
			}
			if(!isdigit(str[i])) return 0;
			for(; i<str.length() && str[i]=='0'; ++i);
			for(int j=i; j<str.length() && isdigit(str[j]); ++j){
				x=x*10+str[j]-'0';
				if(positive && x>INT_MAX) return INT_MAX;
				if(!positive && -x<INT_MIN) return INT_MIN;
			}
			break;
		}
		return positive?x:-x;
	}
};
